package com.alstudio.utils.android.net.http.http2;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;

import android.net.http.AndroidHttpClient;

public class HttpGetRequest {

	public static final String TAG = HttpGetRequest.class.getSimpleName();

	private String url;
	private HttpParameters params = null;
	private HttpParameters headers = null;
	private AndroidHttpClient client;
	private HttpGet getMethod;

	public HttpGetRequest(String url) {
		this.url = url;
	}

	public void addHeader(String name, String value) {
		if (headers == null)
			headers = new HttpParameters();

		headers.add(name, value);
	}

	public void addParameter(String name, String value) {
		if (params == null)
			params = new HttpParameters();

		params.add(name, value);
	}

	public void request(IHttpHandler handler) {
		String requestUrl;

		if (params != null) {
			String param = URLEncodedUtils.format(params.value(), "UTF-8");
			requestUrl = String.format("%s?%s", url, param);
		} else {
			requestUrl = url;
		}

		getMethod = new HttpGet(requestUrl);

		if (headers != null) {
			for (int i = 0; i < headers.size(); ++i) {
				getMethod.setHeader(headers.getKey(i), headers.getValue(i));
			}
		}

		client = AndroidHttpClient.newInstance("");

		try {
			HttpResponse response = client.execute(getMethod);

			if (handler != null) {
				handler.handleResponse(response);
			}

		} catch (IOException e) {
			if (handler != null) {
				handler.handleException(e);
			}

		} finally {
			client.close();
		}
	}

	public void requestAsync(final IHttpHandler handler) {
		new Thread() {

			@Override
			public void run() {
				request(handler);
			}

		}.start();
	}

	public void cancel() {
		if (getMethod != null)
			getMethod.abort();

		if (client != null)
			client.close();
	}

}
